const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const puppeteer = require('puppeteer');
const OpenAI = require('openai');
const cors = require('cors');
const axios = require('axios');
const { v4: uuidv4 } = require('uuid');

// 初始化 Express 应用
const app = express();
app.use(cors());
app.use(express.json());

// 初始化 OpenAI 客户端
const openai = new OpenAI({
  apiKey: '8d060db5-4d82-4104-9473-6fa4ea64905a',
  baseURL: 'https://ark.cn-beijing.volces.com/api/v3',
});

// 封装的 HTTP POST 请求函数
async function httpPost(url, headers, body, timeout) {
  try {
    const response = await axios.post(url, body, {
      headers: headers,
      timeout: timeout
    });
    return response.data;
  } catch (error) {
    console.error('HTTP POST request failed:', error.message);
    throw error;
  }
}

// 语音合成函数
async function synthesis(text) {
  const reqID = uuidv4();
  const params = {
    app: {
      appid: "2558394233",  // 填写平台申请的appid
      token: "xlGafQqqlwGdnX56oXUiw7zKXL6HPmwU",  // token
      cluster: "volcano_tts"  // 填写平台上显示的集群名称
    },
    user: {
      uid: reqID  // 可选，填写用户的真实 ID 以便问题定位
    },
    audio: {
      voice_type: "zh_male_jingqiangkanye_moon_bigtts",  // 填写选中的音色代号
      encoding: "wav",
      speed_ratio: 1.0,
      volume_ratio: 1.0,
      pitch_ratio: 1.0
    },
    request: {
      reqid: reqID,
      text: text,
      text_type: "plain",
      operation: "query"
    }
  };

  const headers = {
    "Content-Type": "application/json",
    "Authorization": `Bearer;xlGafQqqlwGdnX56oXUiw7zKXL6HPmwU`
  };

  const url = "https://openspeech.bytedance.com/api/v1/tts";
  const timeout = 30000;  // 30 秒超时

  try {
    const response = await httpPost(url, headers, JSON.stringify(params), timeout);
    // console.log('Response body:', response);
    console.log('处理成功....正在朗读')
    const respJSON = parseResponse(response);
    const code = respJSON.code;

    if (code !== 3000) {
      console.error('Response code error:', code);
      throw new Error('Response code failed');
    }

    const audio = Buffer.from(respJSON.data, 'base64');
    return audio;
  } catch (error) {
    console.error('Synthesis failed:', error.message);
    throw error;
  }
}

// 解析响应
function parseResponse(response) {
  const { reqid, code, Message, operation, sequence, data } = response;
  return {
    reqid,
    code,
    message: Message,
    operation,
    sequence,
    data
  };
}

// 定义一个新的 API 路由，用于语音合成
app.post('/api/synthesize', async (req, res) => {
  const { text } = req.body;
  console.log('正在向OpenAI处理语音....', req.body)
  if (!text) {
    return res.status(400).json({ error: 'Text is required' });
  }

  try {
    const data = await synthesis(text);
    res.set('Content-Type', 'audio/wav');
    res.send(data);
  } catch (error) {
    res.status(500).json({ error });
  }
});

// 定义抓取数据函数
const fetchData = async (page) => {
  try {
    const data = await page.evaluate(() => {
      const element = document.querySelector("#main-wrapper");
      if (element) {
        return element.outerHTML;
      }
      return null;
    });
    return data;
  } catch (error) {
    return `Error fetching data: ${error.message}`;
  }
};

// 启动 Puppeteer 浏览器和页面
const startBrowser = async () => {
  const browser = await puppeteer.launch({
    headless: false,
    defaultViewport: null,
    executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe',
  });

  const page = await browser.newPage();
  
  // 访问页面
  await page.goto("https://anchor.douyin.com/anchor/dashboard?from=portal&landing_way=scan", {
    waitUntil: "domcontentloaded",
  });

  return { browser, page };
};

// 定义 OpenAI 相关的 API 路由
app.post('/api/get-ai-response', async (req, res) => {
  const { userMessage } = req.body;

  if (!userMessage) {
    return res.status(400).json({ error: 'Missing userMessage in request body' });
  }
  console.log('当前弹幕内容:', userMessage);
  console.log('正在向OpenAI发送API....', userMessage)
  try {
    const completion = await openai.chat.completions.create({
      messages: [
        { role: 'system', content: '你是智宝AI，你现在是直播间的AI人工智能，请回答弹幕的问题' },
        { role: 'user', content: userMessage },
      ],
      model: 'ep-20240811174920-xm9gz', // 确保这是正确的模型 ID
    });

    const aiResponse = completion.choices[0]?.message?.content || 'No content returned';
    console.log('OpenAI返回的内容....', userMessage)
    res.json({ response: aiResponse });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({ error: 'Error processing AI response' });
  }
});

// WebSocket 服务器
const startWebSocketServer = (server, page) => {
  const wss = new WebSocket.Server({ server });

  wss.on('connection', (ws) => {
    console.log('Client connected');
    
    // 定义定时任务
    const intervalId = setInterval(async () => {
      const data = await fetchData(page);
      // console.log(data);
      ws.send(data);
    }, 3000);

    ws.on('close', () => {
      console.log('Client disconnected');
      clearInterval(intervalId);
    });
  });

  console.log('WebSocket server is running');
};

// 启动服务器和 WebSocket 服务器
const main = async () => {
  const { browser, page } = await startBrowser();

  // 创建 HTTP 服务器
  const server = http.createServer(app);

  // 启动 WebSocket 服务器
  startWebSocketServer(server, page);

  // 启动 Express API 服务器
  const PORT = process.env.PORT || 3000;
  server.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
  });

  // 这里你可以加入其他需要的逻辑，例如监听信号来优雅地关闭浏览器
};

main().catch(error => {
  console.error('Error in main function:', error);
});
